﻿using System;
using System.ComponentModel;
using System.Linq.Expressions;
using System.Reflection;
using System.Threading;

namespace Core.Mvvm
{
    public abstract class NotifiedObject : INotifyPropertyChanged
    {
        #region Events

        public event PropertyChangedEventHandler PropertyChanged;

        #endregion

        #region Methods

        protected bool SetProperty<TProperty>(ref TProperty container, TProperty value, Expression<Func<TProperty>> propertyExpression)
        {
            if (object.Equals(value, container))
            {
                return false;
            }
            if (ReferenceEquals(propertyExpression, null))
            {
                throw new ArgumentNullException("propertyExpression");
            }
            container = value;
            OnPropertyChanged(propertyExpression);
            return true;
        }

        protected virtual void OnPropertyChanged<TProperty>(Expression<Func<TProperty>> propertyExpression)
        {
            if (ReferenceEquals(propertyExpression, null))
            {
                throw new ArgumentNullException("propertyExpression");
            }
            string propertyName = GetPropertyName(propertyExpression);
            OnPropertyChanged(propertyName);
        }

        protected static string GetPropertyName<TProperty>(Expression<Func<TProperty>> propertyExpression)
        {
            if (propertyExpression == null)
                throw new ArgumentNullException("propertyExpression");

            MemberExpression memberExpression;

            if (propertyExpression.Body is UnaryExpression)
                memberExpression = ((UnaryExpression)propertyExpression.Body).Operand as MemberExpression;
            else
                memberExpression = propertyExpression.Body as MemberExpression;

            if (memberExpression == null)
                throw new ArgumentException("The expression is not a member access expression", "expression");

            var property = memberExpression.Member as PropertyInfo;
            if (property == null)
                throw new ArgumentException("The member access expression does not access a property", "expression");

            var getMethod = property.GetGetMethod(true);
            if (getMethod.IsStatic)
                throw new ArgumentException("The referenced property is a static property", "expression");

            return memberExpression.Member.Name;
        }

        protected virtual void OnPropertyChanged(string propertyName)
        {
            PropertyChangedEventHandler handler = Interlocked.CompareExchange(ref PropertyChanged, null, null);
            if (handler != null)
            {
                handler(this, new PropertyChangedEventArgs(propertyName));
            }
        }

        #endregion
    }
}
